<template>
  <div class="user-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 下面card区域 -->
    <el-card>
      <!-- 输入框和搜索框 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <!-- input边带搜索图标的输入框，prefix-icon表示前面图标 -->
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="searchWord"
            clearable
          >
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <!-- border边框线、stripe隔行变色 -->
      <el-table :data="userList" style="width: 100%" border stripe height="480">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="sendList">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template v-slot="{ row: arr }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editChang(arr)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delList(arr)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showroleDialogVislble(arr)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <div>没有您想要的数据~~</div>
        </template>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page_num"
        :page-sizes="[5, 10, 20]"
        :page-size="page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchWord ? searchList.length : msg.length"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      title="添加用户"
      @close="dialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        label-width="60px"
        class="demo-addForm"
        ref="addFormRef"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="success" @click="addUser(true)">连续添加</el-button>
        <el-button type="primary" @click="addUser(false)">单个添加</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹窗 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialog"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="editData"
        :rules="editRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 用户名（只读的），手机和邮箱 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="tell">
          <el-input v-model="editData.tell"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editData.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色点击时出现的函数 -->
    <el-dialog title="提示" :visible.sync="roleDialogVislble" width="50%">
      <div>
        <p>当前用户{{ roleInfos.username }}</p>
        <p>当前角色{{ roleInfos.role_name }}</p>
        <p>
          分配新角色&nbsp;
          <el-select v-model="rightValue" placeholder="请选择">
            <el-option
              v-for="item in rightList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVislble = false">取 消</el-button>
        <el-button type="primary" @click="roleDialogVislble = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      // 验证邮箱的规则
      var checkEmail = (rule, value, cb) => {
        // 验证邮箱的正则表达式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          // 合法的邮箱
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号的规则
      var checkMobile = (rule, value, cb) => {
        // 验证手机号的正则
        const regEmail =
          /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regEmail.test(value)) {
          // 合法的号码
          return cb()
        }
        cb(new Error('请输入合法的手机号'))
      }
      return {
        rightList: [
          {
            label: '超级管理员',
            value: 1,
          },
          {
            label: '主管',
            value: 2,
          },
          {
            label: '测试角色',
            value: 3,
          },
        ],
        rightValue: '',
        editDialog: false,
        // 分配角色对话框展示与否
        roleDialogVislble: false,
        searchWord: '',
        // 直接获得的数据
        msg: [],
        page_num: 1,
        page_size: 5,
        dialogVisible: false,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
        },
        addFormRules: {
          username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              min: 2,
              max: 10,
              message: '用户名的长度2-10个字符',
              trigger: 'blur',
            },
          ],
          email: [
            // 验证是否输入了邮箱
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            // 验证是否合法
            {
              validator: checkEmail,
              trigger: 'blur',
            },
          ],
          mobile: [
            { required: true, message: '请输入电话', trigger: 'blur' },
            {
              validator: checkMobile,
              trigger: 'blur',
            },
          ],
        },
        editData: {
          username: '',
          tell: '',
          email: '',
          tmpid: '',
        },
        editRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          tell: [
            { required: true, message: '请输入电话' },
            { validator: checkMobile, trigger: 'blur' },
          ],
          email: [
            { required: true, message: '请输入邮箱' },
            { validator: checkEmail, trigger: 'blur' },
          ],
        },
        roleInfos: {},
      }
    },
    methods: {
      // 展示对话框的函数
      showroleDialogVislble(roleInfo) {
        this.roleInfos.username = roleInfo.username
        this.roleInfos.role_name = roleInfo.role_name
        this.roleDialogVislble = true
      },
      // 修改数据时确定的函数
      confirmEdit() {
        this.$refs.editFormRef.validate((res) => {
          if (!res) {
            return this.$message.error('请检查数据合法性')
          } else {
            let tmpid = this.editData.tmpid
            this.msg.some((item) => {
              if (item.id == tmpid) {
                item.username = this.editData.username
                item.mobile = this.editData.tell
                item.email = this.editData.email
                this.sendList()
                this.$message.success('修改数据成功')
                return true
              }
            })
            console.log(this.editData.tmpid)
            this.editDialog = false
          }
        })
      },
      editClose() {
        this.$refs.editFormRef.resetFields()
      },
      editChang(res) {
        console.log(res.id)
        this.editDialog = true
        this.editData.username = res.username
        this.editData.tell = res.mobile
        this.editData.email = res.email
        this.editData.tmpid = res.id
      },
      delList(arr) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.msg.some((item, i) => {
              if (item.id == arr.id) {
                this.msg.splice(i, 1)
                return true
              }
            })
            this.sendList()
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      getList() {
        let that = this
        this.$http.get('user.php').then(({ data: res }) => {
          that.msg = res
          console.log(that.msg)
        })
      },
      // 发送数据至php的函数
      sendList() {
        let that = this
        this.$http.get('user.php', { params: { list: that.msg } })
      },
      handleSizeChange(newVal) {
        this.page_size = newVal
      },
      handleCurrentChange(newVal) {
        this.page_num = newVal
      },
      // 一个封装的函数，用来决定el-table最终展示的数据
      getuserList(list) {
        if (this.page_size >= list.length) {
          return list
        } else {
          let start = (this.page_num - 1) * this.page_size
          let end =
            this.page_num * this.page_size > list.length
              ? list.length
              : this.page_num * this.page_size
          return list.slice(start, end)
        }
      },
      addUser(val) {
        // 检验表单填写的信息
        this.$refs.addFormRef.validate((res) => {
          if (!res) {
            return this.$message.error('请根据提示修改表单')
            // 下面else进行验证
          } else {
            let that = this
            let id = parseInt(Math.random() * 999)
            let obj = {
              create_time: +new Date(),
              email: that.addForm.email,
              id,
              mg_state: false,
              mobile: that.addForm.mobile,
              role_name: '超级管理员',
              username: that.addForm.username,
            }
            that.msg.unshift(obj)
            that.sendList()
            that.dialogVisible = val
          }
        })
      },
      dialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
    },
    created() {
      this.getList()
    },
    computed: {
      // 这是页面展示的数据
      userList() {
        if (this.searchWord) {
          return this.getuserList(this.searchList)
        } else {
          return this.getuserList(this.msg)
        }
      },
      // 这是搜索的所有数据
      searchList() {
        if (this.searchWord) {
          return this.msg.filter((item) => item.username.match(this.searchWord))
        } else {
          return []
        }
      },
    },
  }
</script>

<style lang='less' scoped>
</style>